package com.hxzy.rabbitmqpublisher.config;

import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;

/**
 * @Author wy
 * @Description 生产者，投递消息，失败回退全局接口
 * @Date 2024/2/23 14:30
 * @Version 1.0
 */
@Log4j2
@Configuration
public class RabbitMqReturnCallbackConfig implements ApplicationContextAware {

    /**
     * 必须在 application.yml中配置
     * publisher-confirm-type: correlated
     * publisher-returns: true
     * template:
     *   mandatory: true
     * @param applicationContext
     * @throws BeansException
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        // 从spring容器中获取RabbitTemplate
        RabbitTemplate rabbitTemplate = applicationContext.getBean(RabbitTemplate.class);

        //发送消息，消息回退(消息一旦发送不成功)的接口实现
        rabbitTemplate.setReturnsCallback(returned -> {
            // 投递失败，记录日志
            log.info("消息发送失败，应答码{}，原因{}，交换机{}，路由键{},消息{}",
                    returned.getReplyCode(), returned.getReplyText(), returned.getExchange(), returned.getRoutingKey(),
                    returned.getMessage().toString());

            //做一些业务逻辑处理
        });



    }
}
